﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using System.Web.UI.WebControls;
using TVR.Timerjobs.Utilitys;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;
using System.Linq;

namespace TVR.Timerjobs.PagesCode
{
    public class TimerjobSettings : GlobalAdminPageBase
    {
        protected PlaceHolder PlaceHolderProperties;
        protected PlaceHolder PlaceHolderScheduleHourly;
        protected PlaceHolder PlaceHolderScheduleMinutely;
        protected PlaceHolder PlaceHolderScheduleDaily;
        protected PlaceHolder PlaceHolderSchedules;

        protected DropDownList ddlTimerjobs;
        protected DropDownList ddlPickSchedule;
        protected Button btnSave;
        protected Button btnRunNow;
        protected Button btnDelete;
        protected Label lblSchedule;

        protected TextBox txtScheduleMinutelyInterval;
        protected TextBox txtScheduleHourlyInterval;
        protected TextBox txtScheduleDailyHour;
        protected TextBox txtScheduleDailyMinute;

        protected Literal ErrorMessageLiteral;

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                SPWebApplication webApp = SPContext.Current.Web.Site.WebApplication;

                //Set event handlers
                btnSave.Click += new EventHandler(btnSave_Click);
                btnRunNow.Click += new EventHandler(btnRunNow_Click);
                btnDelete.Click += new EventHandler(btnDelete_Click);
                btnDelete.Attributes.Add("OnClick", "if (! confirm('Are you sure you want to delete the selected timerjob?')) return false;");
                btnSave.Attributes.Add("OnClick", "if (! confirm('Are you sure you want to save these changes?')) return false;");
                btnRunNow.Attributes.Add("OnClick", "if (! confirm('Are you sure you want to run the selected timerjob now?')) return false;");
               
                //Load the timerjobs dropdown
                LoadTimerjobs(webApp);

                //Hide certain inputfields
                HideAllScheduleInput();

                //Get the jobdef for the currently selected timerjob in dropdown
                SPJobDefinition jobDef = GetSelectedTimerJobDefenition();

                //If a jobdef is found (if there is a custom timerjob selected)
                //display the schedule, new schedule input and properties for it
                if (jobDef != null)
                {
                    DisplaySchedule(jobDef);
                    DisplaySelectedScheduleInput();
                    DisplayProperties(ddlTimerjobs.Text);
                }

               
                base.OnLoad(e);
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = ex.Message.ToString();
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SPWebApplication webApp = SPContext.Current.Web.Site.WebApplication;

            if (string.IsNullOrEmpty(ddlTimerjobs.Text))
            {
                ErrorMessageLiteral.Text = "No timerjob was selected.";
            }
            else
            {
                Utility.RemoveTimerJob(ddlTimerjobs.Text, webApp);
                List<string> tjProperties = new List<string>(); 
                //Remove all properties in propertybag of deleted timerjob
                SPPropertyBag pBag = SPContext.Current.Web.Properties;

                //Only get keys that start with selectedtimerjobName
                var res = from string k in pBag.Keys
                          where k.StartsWith(ddlTimerjobs.Text.ToLower() + "-")
                          select k;

                foreach (string key in res)
                {
                    tjProperties.Add(key);
                }

                foreach(string item in tjProperties)  
                { 
                    pBag.Remove(item);
                }

                pBag.Update();

                RedirectToOperations();
            }
        }

        private void btnRunNow_Click(object sender, EventArgs e)
        {
            SPJobDefinition jobDef = GetSelectedTimerJobDefenition();

            jobDef.Execute(jobDef.Id);

            RedirectToOperations();

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SPJobDefinition jobDef = GetSelectedTimerJobDefenition();

            if (jobDef != null)
            {
                //Save job schedule
                SaveSchedule(jobDef);

                //Save job properties
                SaveProperties(jobDef.Name);

                RedirectToOperations();
            }
            else
            {
                ErrorMessageLiteral.Text = "No timerjob was selected.";
            }
        }

        private void SaveProperties(string jobDefName)
        {
            SPPropertyBag pBag = SPContext.Current.Web.Properties;

            foreach (Control c in PlaceHolderProperties.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    if (c.ID.StartsWith(jobDefName.ToLower() + "-"))
                    {
                        pBag = Utility.SetPropertybagKey(pBag, c.ID, ((TextBox)c).Text);
                    }
                }
            }
        }

        private void SaveSchedule(SPJobDefinition jobDef)
        {
            //Set (new) schedule
            SPSchedule scheduleTj = SetSchedule();
            if (scheduleTj != null)
            {
                //If no new schedule is selected in dropdownlist then old schedule is kept.
                jobDef.Schedule = scheduleTj;
            }

            jobDef.Update();
        }

        private void RedirectToOperations()
        {
            this.RedirectToOperationsPage();
        }

        #endregion

        #region getData

        private SPJobDefinition GetSelectedTimerJobDefenition()
        {
            //Only get keys that start with selectedtimerjobName
            var res = from SPJobDefinition jd in SPContext.Current.Web.Site.WebApplication.JobDefinitions
                      where jd.Title == ddlTimerjobs.Text
                      select jd;

            if (res != null && res.Count() > 0)
            {
                return res.First();
            }
            else
            {
                return null;
            }
        }

        private void LoadTimerjobs(SPWebApplication webApp)
        {
            if (!Page.IsPostBack)
            {
                ddlTimerjobs.Items.Clear();
                foreach (SPJobDefinition jd in webApp.JobDefinitions)
                {
                    ddlTimerjobs.Items.Add(jd.Title);
                }
            }

            if (ddlTimerjobs.Items.Count < 1)
            {
                ErrorMessageLiteral.Text = "No custom timerjobs were found.";
            }
        }

        private void DisplayProperties(string timerjobName)
        {
            PlaceHolderProperties.Controls.Clear();
            SPPropertyBag pBag = SPContext.Current.Web.Properties;

            //Only get keys that start with selectedtimerjobName
            var res = from string k in pBag.Keys
                      where k.StartsWith(timerjobName.ToLower() + "-")
                      select k;

            foreach (string key in res)
            {
                Label lblKey = new Label();
                lblKey.Text = key.Replace(timerjobName.ToLower() + "-","");

                TextBox txtValue = new TextBox();
                txtValue.ID = key;
                txtValue.Text = pBag[key];

                PlaceHolderProperties.Controls.Add(new LiteralControl(@"<table width=""100%"" class=""ms-authoringcontrols"">"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<tr>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<td>"));
                PlaceHolderProperties.Controls.Add(lblKey);
                PlaceHolderProperties.Controls.Add(new LiteralControl("</td>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<td>"));
                PlaceHolderProperties.Controls.Add(txtValue);
                PlaceHolderProperties.Controls.Add(new LiteralControl("</td>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("</tr>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl(@"</table>"));
            }
        }

        private void DisplaySchedule(SPJobDefinition jd)
        {
            lblSchedule.Text = jd.Schedule.ToString();
        }

        #endregion

        #region schedule

        private void DisplaySelectedScheduleInput()
        {

            if(!string.IsNullOrEmpty(ddlPickSchedule.SelectedValue))
                PlaceHolderSchedules.FindControl(ddlPickSchedule.SelectedValue).Visible = true;
        }

        private void HideAllScheduleInput()
        {
            PlaceHolderScheduleHourly.Visible = false;
            PlaceHolderScheduleDaily.Visible = false;
            PlaceHolderScheduleMinutely.Visible = false;
        }

        private SPSchedule SetSchedule()
        { 

            switch (ddlPickSchedule.SelectedValue)
            {
                case "PlaceHolderScheduleMinutely":
                    SPMinuteSchedule scheduleMin = new SPMinuteSchedule();
                    scheduleMin.BeginSecond = 0;
                    scheduleMin.EndSecond = 0;
                    int intervalMin;
                    if (int.TryParse(txtScheduleMinutelyInterval.Text, out intervalMin))
                        intervalMin = int.Parse(txtScheduleMinutelyInterval.Text);
                    else
                    {
                        throw new Exception("The interval for minutes in your timerjob schedule must be numeric");
                    }
                    scheduleMin.Interval = intervalMin;
                    return scheduleMin;
                case "PlaceHolderScheduleHourly":
                    SPHourlySchedule scheduleHour = new SPHourlySchedule();
                    
                    int beginMin;
                    if (int.TryParse(txtScheduleHourlyInterval.Text, out beginMin))
                        beginMin = int.Parse(txtScheduleHourlyInterval.Text);
                    else
                    {
                        throw new Exception("The beginminute in your timerjob schedule must be numeric");
                    }
                    scheduleHour.BeginMinute = beginMin;
                    scheduleHour.EndMinute = beginMin;
                    return scheduleHour;
                case "PlaceHolderScheduleDaily":
                    SPDailySchedule scheduleDay = new SPDailySchedule();
                    
                    int startHour;
                    if (int.TryParse(txtScheduleDailyHour.Text, out startHour))
                        startHour = int.Parse(txtScheduleDailyHour.Text);
                    else
                    {
                        throw new Exception("The startHour in your timerjob schedule must be numeric");
                    }

                    int startMinute;
                    if (int.TryParse(txtScheduleDailyMinute.Text, out startMinute))
                        startMinute = int.Parse(txtScheduleDailyMinute.Text);
                    else
                    {
                        throw new Exception("The hour in your timerjob schedule must be numeric");
                    }

                    scheduleDay.BeginHour = startHour;
                    scheduleDay.BeginMinute = startMinute;
                    scheduleDay.BeginSecond = 0;
                    scheduleDay.EndHour = startHour;
                    scheduleDay.EndMinute = startMinute;
                    scheduleDay.EndSecond = 0;
                    return scheduleDay;
                default:
                    //If none of the above was selected then don't change schedule
                    return null;
            }
        }

        #endregion


       
    }
}
